<template>
  <a-modal
    :open="visible"
    :title="title"
    width="416px"
    centered
    :ok-button-props="{ loading: loading }"
    @cancel="handleCancel"
    @ok="handleSubmit"
  >
    <a-form ref="formRef" :model="formState" :rules="taskRules" layout="vertical">
      <a-form-item label="文件夹名称" name="name">
        <a-input v-model:value="formState.name" v-trim placeholder="请输入文件夹名称" :maxlength="200" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
  import { FormInstance } from 'ant-design-vue'
  import type { Rule } from 'ant-design-vue/es/form'
  import { ref } from 'vue'

  import { validateBitLen, validateDirName } from '@/utils'

  interface OpenOptions {
    visible: boolean
    title: string
    type: 'add' | 'edit'
  }

  // const emit = defineEmits(['ok', 'cancel'])
  const emits = defineEmits<{ (e: 'ok', params: 'add' | 'edit', obj: any): void; (e: 'cancel'): void }>()

  const visible = ref(false)
  const loading = ref(false)
  const title = ref<string>()
  const type = ref<'add' | 'edit'>('add')
  let options: any = null
  const formRef = ref<FormInstance>()

  const formState = ref({
    name: ''
  })
  const taskRules: Record<string, Rule[]> = {
    name: [
      { required: true, message: '请输入文件夹名称', trigger: 'change' },
      { validator: validateDirName() },
      { validator: validateBitLen(200), trigger: 'change' }
    ]
  }

  const handleSubmit = async () => {
    try {
      const values = await formRef.value?.validate()
      emits('ok', type.value, { ...options, ...values })
    } catch (error) {
      console.log(error)
    }
  }
  const handleCancel = () => {
    formRef.value?.resetFields()
    hide()
    emits('cancel')
  }

  const open = (options: OpenOptions) => {
    visible.value = options.visible
    title.value = options.title || ''
    type.value = options.type || 'add'
  }

  const hide = () => {
    formState.value.name = ''
    visible.value = false
  }

  const setData = (data: any) => {
    formState.value.name = data.name
    options = data
  }

  const changeLoading = (status: boolean) => {
    loading.value = status
  }

  defineExpose({
    changeLoading,
    open,
    hide,
    setData
  })
</script>
